import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { RentalList } from '@app/store/dict';
import { IGrid, IGridHouseholdInfo } from '@model/grid';
import { AuthService } from '@service/auth.service';
import { GridService } from '@service/grid.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { GridHouseholdEditComponent } from './grid-household-edit/grid-household-edit.component';
import { toCanvas } from 'qrcode';

@Component({
	selector: 'app-grid-household',
	templateUrl: './grid-household.component.html',
	styleUrls: ['./grid-household.component.less']
})
export class GridHouseholdComponent extends AbsFormUtil implements OnInit {
	@ViewChild('inputFile') inputFile: any;
	rentalList = RentalList;
	nzLoading = false;
	data = [];
	constructor(
		private gridService: GridService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalService: NzModalService,
		private authService: AuthService
	) {
		super();
		this.authList = this.authService.getAuth();
	}


	ngOnInit() {
		this.buildForm();
		this.onSearch();
	}
	buildForm() {
		this.validateForm = this.fb.group({
			address: [''],
			contact: [''],
			contractNumber: [''],
			rental: [''],
			householdCode: [''],
			housemaster: [''],
			housemasterContactNum: [''],
		});
	}

	async onSearch(isPageInit?: boolean) {
		this.nzLoading = true;
		if (isPageInit) {
			this.page.page = 1;
		}
		const formValue = this.validateForm.value;
		const params = { ...formValue, ...this.page };
		const result = await this.gridService.getHouseholdList(params);
		this.data = result.data.list;
		this.page.total = result.data.totalCount;
		this.nzLoading = false;
	}


	pageChange(isPageInit?: boolean) {
		if (isPageInit) {
			this.page.page = 1;
		}
		this.onSearch();
	}



	async del(item) {
		await this.gridService.deleteHousehold(item.id);
		this.nzMessageService.success('删除成功');
		this.onSearch(true);
	}



	add(item?: IGridHouseholdInfo) {
		this.nzModalService.create({
			nzTitle: item ? '编辑村户' : '村户新增',
			nzContent: GridHouseholdEditComponent,
			nzBodyStyle: {
				padding: '0 20px',
			},
			nzStyle: {
				top: '50px'
			},
			nzWidth: '70%',
			nzComponentParams: {
				id: item?.id
			},
			nzFooter: [
				{
					label: '确定',
					type: 'primary',
					onClick: (componentInstance) => {
						(async () => {
							const formRes = componentInstance.onSubmit();
							if (formRes) {
								formRes.areaId = formRes.areaId ? formRes.areaId[formRes.areaId.length - 1] : '';
								formRes.tags = formRes.tags ? formRes.tags.join(',') : '';
								formRes.id = componentInstance.id || '';
								formRes.rental = formRes.rental ? '1' : '0';
								formRes.tenements = [];
								formRes.registers = [];
								if (formRes.rental === '1') {
									formRes.tenements = formRes.lists;
								}
								if (formRes.rental === '0') {
									formRes.registers = formRes.lists;
								}
								delete formRes.lists;
								const result = await this.gridService.saveHousehold(formRes);
								if (result.status !== 0) {
									this.nzMessageService.error('保存失败，请稍后');
									return;
								}
								componentInstance.id ? this.onSearch() : this.onSearch(true);
								this.nzMessageService.success('保存成功');
								componentInstance.destroyModal();

							}
						})();
					}
				},
				{
					label: '取消',
					onClick: componentInstance => {
						componentInstance.destroyModal();
					}
				}
			]
		})
	}
	qrDownload(item) {
		const url = item?.qrcode || '暂无字段,请稍后再试';
		const {areaName, address} = item;
		toCanvas(url, { width: 150, margin: 0 }).then(canvas => {
			const canvasImg = canvas.toDataURL("image/png");
			this.downloadFile(`${areaName ? areaName : ''}${areaName&&address ? ',' : ''}${address ? address : ''}`, canvasImg);
		})
	}

	createQr(isShow:boolean, item) {
		if (!isShow) {
			return
		}
		setTimeout(() => {
			const canvas = document.getElementById(`qrid${item.id}`) as HTMLCanvasElement;
			const url = item?.qrcode || '暂无字段,请稍后再试';
			toCanvas(canvas, url, { width: 150, margin: 0 }, (error) => {
				if (error) {
					console.log(error);
				}
			});
		});
		
	}


	downloadFile(filename, content) {
        const base64Img = content;
        const oA = document.createElement('a');
        oA.href = base64Img;
        oA.download = filename;
        const event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        oA.dispatchEvent(event);
    }

	upload() {
		(this.inputFile.nativeElement as HTMLInputElement).click()
	}

	async uploadFile(event: Event){
		const ele = event.target as HTMLInputElement;
		const fileList = Array.prototype.slice.call(ele.files);
		console.log(fileList);
		// const formData = new FormData();
 		// formData.append('file', this.upload.file);
		// e.target.value = null;
		this.nzMessageService.success('上传成功');
		this.onSearch(true);
	}
}
